package com.erp.erp_servers.ShipmentPlan.imp;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.erp.erp_dao.Company.ICompanyDAO;
import com.erp.erp_dao.Customer2.ICustomer2DAO;
import com.erp.erp_dao.ShipmentPlan.IShipmentPlanCostDAO;
import com.erp.erp_dao.ShipmentPlan.IShipmentPlanDAO;
import com.erp.erp_dao.ShipmentPlan.IShipmentPlanFileDAO;
import com.erp.erp_dao.ShipmentPlan.IShipmentPlanProductDAO;
import com.erp.erp_dao.ShipmentPlanLog.IShipmentPlanLogDAO;
import com.erp.erp_entitys.Customer.CustomerEntity;
import com.erp.erp_entitys.Customer2.Customer2Entity;
import com.erp.erp_entitys.Department.DepartmentEntity;
import com.erp.erp_entitys.Department.DepartmentExample;
import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.ShipmentPlan.*;
import com.erp.erp_entitys.ShipmentPlanLog.ShipmentPlanLog;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.money.rsp.PaymentStatistics1Rsp;
import com.erp.erp_servers.Company.ICompanyService;
import com.erp.erp_servers.Customer.ICustomerService;
import com.erp.erp_servers.Department.IDepartmentService;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.InspectCargo.IInspectCargoService;
import com.erp.erp_servers.ShipmentPlan.IShipmentPlanService;
import com.erp.erp_servers.User.IUserService;
import com.erp.utils.DateUtils;
import com.erp.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
public class ImpShipmentPlanService implements IShipmentPlanService {

    @Autowired
    private IShipmentPlanDAO shipmentPlanDAO;
    @Autowired
    private IShipmentPlanProductDAO productDAO;
    @Autowired
    private IShipmentPlanCostDAO costDAO;
    @Autowired
    private IShipmentPlanFileDAO fileDAO;
    @Autowired
    private IShipmentPlanLogDAO shipmentPlanLogDAO;
    @Autowired
    IDictionary2Service dictionary2Service;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    ICompanyDAO companyDAO;

    @Autowired
    IInspectCargoService inspectCargoService;

    @Autowired
    IDepartmentService departmentService;

    @Autowired
    private ICustomer2DAO customer2DAO;
    @Override
    @Transactional
    public int deleteByPrimaryKey(Integer id) {
        int num = shipmentPlanDAO.deleteByPrimaryKey(id);
        //删除产品
        // int deleteByIdList(@Param("idList") List<Integer> idList);
        List<ShipmentPlanProduct> shipmentPlanProducts = productDAO.selectProductByShipmentPlanId(id);
        List<Integer> productList = new ArrayList<>();
        for (int i = 0; i < shipmentPlanProducts.size(); i++) {
            productList.add(shipmentPlanProducts.get(i).getId());
        }
        int p = 0;
        if (productList.size() > 0) {
            p = productDAO.deleteByIdList(productList);
        }
        //删除费用
        List<ShipmentPlanCost> shipmentPlanCosts = costDAO.selectCostBySpId(id);
        List<Integer> costtList = new ArrayList<>();
        int c = 0;
        for (int i = 0; i < shipmentPlanCosts.size(); i++) {
            costtList.add(Integer.parseInt(shipmentPlanCosts.get(i).getId().toString()));
        }
        if (costtList.size() > 0) {
            c = costDAO.deleteByIdList(costtList);
        }
        //删除文件
        List<ShipmentPlanFile> shipmentPlanFiles = fileDAO.selectFileBySpId(id);
        List<Integer> fileList = new ArrayList<>();
        int f = 0;
        for (int i = 0; i < shipmentPlanFiles.size(); i++) {
            fileList.add(shipmentPlanFiles.get(i).getId());
        }
        if (fileList.size() > 0) {
            f = fileDAO.deleteByIdList(fileList);
        }
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ShipmentPlan record) {
        ShipmentPlanLog log = new ShipmentPlanLog();
        log.setOperationdate(new Date());
        log.setOpname(record.getExecutorCode());

        if (record == null) {
            return 0;
        }
        ShipmentPlan shipmentPlan = new ShipmentPlan();
        int num = 0;
        if (null != record.getId()) {
            shipmentPlan.setId(record.getId());
            num = shipmentPlanDAO.updateByPrimaryKeySelective(record);
            log.setShipmentplanid(record.getId());
            log.setOperationtype("更新");
            log.setModifythecontent("对出运计划主信息进行修改");
            shipmentPlanLogDAO.insert(log);
        } else {
            num = shipmentPlanDAO.insert(record);
            shipmentPlan = shipmentPlanDAO.selectInfoByCode(record.getShipmentNo());
            log.setShipmentplanid(shipmentPlan.getId());
            log.setOperationtype("新增");
            log.setModifythecontent("新增了出运计划主信息");
            shipmentPlanLogDAO.insert(log);
        }

        //ShipmentPlan shipmentPlan1 = shipmentPlanDAO.selectInfoById(record.getId());
        //shipmentPlan = shipmentPlanDAO.selectInfoByCode(record.getShipmentNo());
        if (num > 0) {
            List<ShipmentPlanProduct> productList = record.getProductList();
            if (!CollectionUtils.isEmpty(productList)) {

                for (ShipmentPlanProduct pro : productList) {
                    pro.setShipmentPlanId(shipmentPlan.getId());
                    if (null != pro.getId()) {
                        productDAO.updateByPrimaryKey(pro);
                        log.setOperationtype("更新");
                        log.setModifythecontent("更新了产品信息");
                        shipmentPlanLogDAO.insert(log);
                    } else {
                        productDAO.insert(pro);
                        log.setOperationtype("新增");
                        log.setModifythecontent("新增了产品信息");
                        shipmentPlanLogDAO.insert(log);
                    }
                }

            }
            List<ShipmentPlanCost> costList = record.getCostList();
            if (!CollectionUtils.isEmpty(costList)) {

                for (ShipmentPlanCost cost : costList) {
                    cost.setShipmentPlanId(shipmentPlan.getId());
                    if (null != cost.getId()) {
                        log.setOperationtype("更新");
                        log.setModifythecontent("更新了费用信息");
                        costDAO.updateByPrimaryKey(cost);

                    } else {
                        costDAO.insert(cost);
                        log.setOperationtype("新增");

                        //获取费用类型
                        Map<String, Object> map = getValues(5, 19);
                        String costName="";
                        for (String p:map.keySet()) {
                            if (p.equals(cost.getCostType())){
                                costName= (String) map.get(p);
                                break;
                            }
                        }


                        log.setModifythecontent("新增新增了费用信息 (费用类型："+costName+"，费用金额："+cost.getCostMoney()+"，费用描述："+cost.getCostDesc()+")");
                    }
                    shipmentPlanLogDAO.insert(log);
                }
            }
            List<ShipmentPlanFile> fileList = record.getFileList();
            if (!CollectionUtils.isEmpty(fileList)) {
                for (ShipmentPlanFile file : fileList) {
                    file.setShipmentPlanId(shipmentPlan.getId());
                    file.setFileExecutor(record.getExecutorCode());
                    String fileName = file.getFileName();
                    if (!StringUtils.isEmpty(fileName)) {
                       // if (StringUtils.isEmpty(file.getFileType())) {
                            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                            file.setFileType(suffix);
                       // }
                    }
                    file.setFileUploadTime(new Date(System.currentTimeMillis()));
                    if (null != file.getId()) {
                        fileDAO.updateByPrimaryKey(file);
                        log.setOperationtype("更新");
                        log.setModifythecontent("更新了文件信息");
                    } else {
                        fileDAO.insert(file);
                        log.setOperationtype("新增");
                        log.setModifythecontent("新增了文件信息");
                    }
                    shipmentPlanLogDAO.insert(log);
                }
            }
        }
        return num;
    }

    @Override
    public int insertSelective(ShipmentPlan record) {
        return shipmentPlanDAO.insertSelective(record);
    }

    @Override
    public ShipmentPlan selectByPrimaryKey(Integer id) {
        ShipmentPlan shipmentPlan = shipmentPlanDAO.selectByPrimaryKey(id);
       /* CustomerExample example = new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(shipmentPlan.getCustomerCode());
        List<CustomerEntity> customerEntities = customerService.selectByExample(example);
        try {
            shipmentPlan.setCustomerCode(customerEntities.get(0).getName());
        }catch (Exception e){
            e.printStackTrace();
        }*/
        return shipmentPlan;
    }

    @Override
    public int updateByPrimaryKeySelective(ShipmentPlan record) {
        return shipmentPlanDAO.updateByPrimaryKeySelective(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKey(ShipmentPlan record) {
        if (record == null || null == record.getId() || "".equals(record.getId())) {
            return 0;
        }
        ShipmentPlanLog log = new ShipmentPlanLog();
        log.setOperationdate(new Date());
        log.setOpname(record.getExecutorCode());
        log.setShipmentplanid(record.getId());
        log.setOperationtype("更新");

        //原数据
        ShipmentPlan oldShipmentPlan = shipmentPlanDAO.selectByPrimaryKey(record.getId());
        int num = shipmentPlanDAO.updateByPrimaryKey(record);
        String modifyTheContent="修改出运计划";//修改内容
        //修改价格术语添加进日志
        if (!oldShipmentPlan.getPriceTerm().equals(record.getPriceTerm())){
            String oldPriceTerm="";
            String recPriceTerm="";
            if (!StringUtils.isEmpty(oldShipmentPlan.getPriceTerm())){
                DictionaryEntity oldDictionary = dictionary2Service.selectByParam(5, 16,oldShipmentPlan.getPriceTerm());
                if (oldDictionary!=null){
                    oldPriceTerm=oldDictionary.getName();
                }
            }
            if (!StringUtils.isEmpty(record.getPriceTerm())){
                DictionaryEntity recDictionary = dictionary2Service.selectByParam(5, 16,record.getPriceTerm());
                if (recDictionary!=null){
                    recPriceTerm=recDictionary.getName();
                }
            }
            modifyTheContent="修改出运计划主信息价格术语字段，原价格术语："+oldPriceTerm+"，原价格术语编码："+oldShipmentPlan.getPriceTerm()+"，现价格术语："+recPriceTerm+"，现价格术语编码："+record.getPriceTerm();
        }
        log.setModifythecontent(modifyTheContent);
        shipmentPlanLogDAO.insert(log);

        if (num > 0) {
            List<ShipmentPlanProduct> productList = record.getProductList();
            List<ShipmentPlanProduct> dbProductList = productDAO.selectProductByShipmentPlanId(record.getId());//selectProductBySpId
            if (!CollectionUtils.isEmpty(dbProductList)) {
                List<Integer> idList = new ArrayList<Integer>();
                for (ShipmentPlanProduct dbProduct : dbProductList) {
                    idList.add(dbProduct.getId());
                }
                if (idList.size() > 0) {
                    productDAO.deleteByIdList(idList);
                }
            }
            if (!CollectionUtils.isEmpty(productList)) {
                for (ShipmentPlanProduct pro : productList) {
                    pro.setShipmentPlanId(record.getId());
                    productDAO.insert(pro);
                }
            }
            List<ShipmentPlanCost> costList = record.getCostList();
            List<ShipmentPlanCost> dbCostList = costDAO.selectCostBySpId(record.getId());
            if (!CollectionUtils.isEmpty(dbProductList)) {
                List<Integer> idList = new ArrayList<Integer>();
                for (ShipmentPlanCost dbCost : dbCostList) {
                    idList.add(dbCost.getId().intValue());
                }
                if (idList.size() > 0) {
                    costDAO.deleteByIdList(idList);
                }
            }
            if (!CollectionUtils.isEmpty(costList)) {
                for (ShipmentPlanCost cost : costList) {
                    cost.setShipmentPlanId(record.getId());
                    costDAO.insert(cost);
                }
            }
            List<ShipmentPlanFile> fileList = record.getFileList();
            List<ShipmentPlanFile> dbFileList = fileDAO.selectFileBySpId(record.getId());
            if (!CollectionUtils.isEmpty(dbFileList)) {
                List<Integer> idList = new ArrayList<Integer>();
                for (ShipmentPlanFile dbFile : dbFileList) {
                    idList.add(dbFile.getId());
                }
                if (idList.size() > 0) {
                    fileDAO.deleteByIdList(idList);
                }
            }
            if (!CollectionUtils.isEmpty(fileList)) {
                for (ShipmentPlanFile file : fileList) {
                    file.setShipmentPlanId(record.getId());
                    file.setFileExecutor(record.getExecutorCode());
                    String fileName = file.getFileName();
                    if (!StringUtils.isEmpty(fileName)) {
                        //if (StringUtils.isEmpty(file.getFileType())) {
                            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                            file.setFileType(suffix);
                        //}
                    }
                    file.setFileUploadTime(new Date(System.currentTimeMillis()));
                    fileDAO.insert(file);
                }
                /*if (null != record.getId()) {
                    for (ShipmentPlanFile file : fileList) {
                        file.setShipmentPlanId(record.getId());
                        file.setFileExecutor(record.getExecutorCode());
                        String fileName = file.getFileName();
                        if (!StringUtils.isEmpty(fileName)) {
                            if (StringUtils.isEmpty(file.getFileType())) {
                                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                                file.setFileType(suffix);
                            }
                        }
                        file.setFileUploadTime(new Date(System.currentTimeMillis()));
                        if(file.getId()==null){
                            fileDAO.insert(file);
                        }else{
                            fileDAO.updateByPrimaryKey(file);
                        }

                    }
                } else {
                    for (ShipmentPlanFile file : fileList) {
                        file.setShipmentPlanId(record.getId());
                        file.setFileExecutor(record.getExecutorCode());
                        String fileName = file.getFileName();
                        if (!StringUtils.isEmpty(fileName)) {
                            if (StringUtils.isEmpty(file.getFileType())) {
                                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                                file.setFileType(suffix);
                            }
                        }
                        file.setFileUploadTime(new Date(System.currentTimeMillis()));
                        fileDAO.insert(file);
                    }
                }*/

            }
        }
        return num;
    }

    @Override
    public List<ShipmentPlan> selectShipmentPlanList(ShipmentPlanVo vo) {
        List<ShipmentPlan> list = shipmentPlanDAO.selectShipmentPlanList(vo);
        conver(list);
        //将数据中对应的编码转换为名称
        return list;
    }

    private void conver(List<ShipmentPlan> list) {
        Map<String, Object> curry=getValues(5,14);//币种
        Map<String, Object> termspay=getValues(5,18);//收款方式
        Map<String, Object> priceterm=getValues(5,16);//价格术语
        Map<String, Object> business=getValues(6,20);//业务模式
        Map<String, Object> destin = getValues(6,29); //目的地
        Map<String, Object> places = getValues(6,31); //起运地
        Map<String, Object> declarecompany=getValues(6,48);//报关抬头
        Map<String, Object> stock=getValues(4,11);//仓库
        /*Map<String, Object> company = getCompany();   //签约公司
        Map<String, Object> user = getUser();   //获取用户
        Map<String, Object> customer=getCustomer();//客户
        Map<String, Object> boxStatus=getBosstatus();//*/


        List<UserEntity> allUserNameAndCode = userService.getAllUserNameAndCode();
        Map<String,String> userMap=new HashMap<>();
        for(UserEntity ue:allUserNameAndCode){
            userMap.put(ue.getCode(),ue.getName());
        }

        Map<String,Object> boxStatus=new HashMap<>();
        boxStatus.put("1","草稿");
        boxStatus.put("2","待批");
        boxStatus.put("3","已批");
        boxStatus.put("4","完成");
        boxStatus.put("5","垃圾");
        List<String> qygs=new ArrayList<>();
        List<String> customers=new ArrayList<>();
      for(ShipmentPlan sp:list){
          sp.setCurrency(converString(curry.get(sp.getCurrency())));
          sp.setPaymentTerm(converString(termspay.get(sp.getPaymentTerm())) );
          sp.setPriceTerm(converString(priceterm.get(sp.getPriceTerm())) );
          sp.setBusinessMode(converString(business.get(sp.getBusinessMode())));
          sp.setEndPlace(converString(destin.get(sp.getEndPlace())));
          sp.setStartPlace(converString(places.get(sp.getStartPlace())));
          sp.setDeclareCompany(converString(declarecompany.get(sp.getDeclareCompany())));
          sp.setStock(converString(stock.get(sp.getStock()) ));
         // sp.setBoxStatus(converString(boxStatus.get(sp.getBoxStatus()) ));
          sp.setExecutorCode(userMap.get(sp.getExecutorCode()));
          sp.setSalesmanCode(userMap.get(sp.getSalesmanCode()));
         /* qygs.add(sp.getCompanyCode());
          customers.add(sp.getCustomerCode());*/
      }




    }
    private String converString(Object value){
        if(null == value || value.equals("")){
            return "";
        }else{
            return value.toString();
        }
    }
    @Override
    public PageInfo<ShipmentPlan> selectByIdList(List<Integer> list) {
        List<ShipmentPlan> spList = shipmentPlanDAO.selectByIdList(list);
        PageInfo pageInfo = new PageInfo(spList);
        if (CollectionUtils.isEmpty(spList)) {
            pageInfo.setList(null);
            return pageInfo;
        }
        pageInfo.setList(spList);
        pageInfo.setTotal(spList.size());
        return pageInfo;
    }

    @Override
    public int updateBoxStatusByKey(ShipmentPlanVo vo,String userCode) {
        int num=0;

        num= shipmentPlanDAO.updateBoxStatusByKey(vo);

        if (vo.getBoxStatus().equals("4")){
            ShipmentPlanLog log = new ShipmentPlanLog();
            log.setShipmentplanid(vo.getId().intValue());
            log.setOperationtype("审批完成");
            log.setOperationdate(new Date());
            log.setOpname(userCode);
            log.setModifythecontent("单据操作");
            shipmentPlanLogDAO.insert(log);
        }
        if (vo.getBoxStatus().equals("2")){
            ShipmentPlanLog log = new ShipmentPlanLog();
            log.setShipmentplanid(vo.getId().intValue());
            log.setOperationtype("提交审批");
            log.setOperationdate(new Date());
            log.setOpname(userCode);
            log.setModifythecontent("单据操作");
            shipmentPlanLogDAO.insert(log);
        }

        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBoxStatusByKey2(ShipmentPlanVo vo, String shipmentNO,String userCode) {
        int num=0;
        num= shipmentPlanDAO.updateBoxStatusByKey(vo);

        //日志
        ShipmentPlanLog log = new ShipmentPlanLog();
        log.setShipmentplanid(vo.getId().intValue());
        log.setOperationdate(new Date());
        log.setOpname(userCode);
        log.setModifythecontent("单据操作");

        if(vo.getBoxStatus().equals("3") && num==1){
            //审批通过
            //先删除
            num= inspectCargoService.delInspectCargoByLoadPlanNo(shipmentNO);

            //再插入
            num=inspectCargoService.generateInspectCargoByShipmentNo(shipmentNO);

            log.setOperationtype("审批通过");
        }else if(vo.getBoxStatus().equals("1") && num==1){
            //审批退回
            //先删除
            num= inspectCargoService.delInspectCargoByLoadPlanNo(shipmentNO);

            log.setOperationtype("审批退回");
        }

        shipmentPlanLogDAO.insert(log);

        return num;
    }

    @Override
    public ShipmentPlan selectInfoById(Integer id) {
        return shipmentPlanDAO.selectInfoById(id);
    }

    @Override
    public boolean isExist(String oddNumber) {
        List<ShipmentPlan> existList = shipmentPlanDAO.isExist(oddNumber);
        return  CollectionUtils.isEmpty(existList) ? false : true;
    }

    @Override
    public List<ShipmentPlan> findShipmentPlanByCode(String code) {
        return shipmentPlanDAO.isExist(code);
    }

    @Override
    public boolean getCount(String oddNumber) {
        List<ShipmentPlan> existList = shipmentPlanDAO.isExist(oddNumber);
        int count = shipmentPlanDAO.getCount(oddNumber);
        return count ==0 ? false:true;//CollectionUtils.isEmpty(existList) ? false : true;
    }

    /**
     * 根据外销（备货）合同号、产品id查询出运计划中的产品数据信息
     *
     * @param billNo
     * @param productNo
     * @param specNo
     * @return
     */
    @Override
    public int getPlanProduct(String billNo, String productNo, String specNo) {
        ShipmentPlanProduct spp = new ShipmentPlanProduct();
        spp.setProductNo(productNo);
        spp.setSpecNo(specNo);
        spp.setExportContractNo(billNo);
        int amount = productDAO.getPlanProduct(spp);
        return amount;
    }

    /**
     * 根据外销（备货）合同号、产品id查询出运计划中的产品数据信息
     *
     * @param billNo
     * @param productNo
     * @param specNo
     * @param productId 明细id
     * @return
     */
    @Override
    public int getPlanProductNum(String billNo, String productNo, String specNo, Integer productId) {
        ShipmentPlanProduct spp = new ShipmentPlanProduct();
        spp.setProductNo(productNo);
        spp.setSpecNo(specNo);
        spp.setExportContractNo(billNo);
        spp.setProductId(productId);
        int amount = productDAO.getPlanProductNum(spp);
        return amount;
    }

    /**
     * 获取字典
     * @param type
     * @param lx
     * @return
     */
    private Map<String, Object> getValues(Integer type, Integer lx) {
        List<DictionaryEntity> value = dictionary2Service.getValue(type, lx);
        Map<String ,Object> map=new HashMap<>();
        for (int i = 0; i < value.size(); i++) {
            DictionaryEntity de = value.get(i);
            if (de.getCode() != null) {
                map.put(de.getCode(),de.getName());
            }
        }
      return map;
    }


    /**
     * 获取出运结汇一览总表集合
     * @param req
     * @return
     */
    public List<ShipmentPlanStatistics1Res> getStatistics1ResList(ShipmentPlanStatistics1Req req){
        List<ShipmentPlanStatistics1Res> statistics1ResList=shipmentPlanDAO.shipmentPlanStatistics1(req);

        for (ShipmentPlanStatistics1Res p:statistics1ResList ) {
            if (p.getSupplierCode()!=null){
                Customer2Entity customer2Entity=customer2DAO.selectByCode(p.getSupplierCode());
                if (customer2Entity!=null){
                    p.setSupplyerName(customer2Entity.getName());
                }
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(p.getCustomerCode())){
                CustomerEntity customer=customerService.findCustomerByCode(p.getCustomerCode());
                if (customer!=null){
                    p.setCustomerName(customer.getName());
                }
            }
            p.setShipmentDateStr(DateUtils.format(p.getShipmentDate(),DateUtils.DATE_PATTERN));
            p.setCreateTimeStr(DateUtils.format(p.getCreateTime(),DateUtils.DATE_PATTERN));
            p.setUnCarryPlanProductNum(p.getShipmentPlanNum().subtract(p.getCarryPlanProductNum()));
            p.setUnBillExchangeInfoNum(p.getCarryPlanProductNum().subtract(p.getBillExchangeInfoNum()));
            switch (p.getProductType()){
                case "1" :
                    p.setProductType("成品") ;
                    break;
                case "2" :
                    p.setProductType("配件");
                    break;
            }
        }
        return statistics1ResList;
    }
    @Override
    public PageInfo<ShipmentPlanStatistics1Res> shipmentPlanStatistics1(ShipmentPlanStatistics1Req req) {
        List<ShipmentPlanStatistics1Res> statistics1ResList=getStatistics1ResList(req);
        PageInfo pageInfo=new PageInfo(statistics1ResList);
        return pageInfo;
    }
    /**
     * 获取String类型不为空数据
     * @param value 目标数据
     * @return 不为空数据
     */
    private String getNotNullOfStringInfo(String value){
        if(org.apache.commons.lang3.StringUtils.isEmpty(value)){
            return "";
        }else {
            return value;
        }
    }

    /**
     * 获取BigDecimal类型不为空的数据
     * @param value 目标数据
     * @return 不为空数据
     */
    private BigDecimal getNotNullOfBigDecimalInfo(BigDecimal value){
        if(StringUtil.isNotEmpty(value)){
            return value;
        }else {
            return new BigDecimal("0");
        }
    }
    @Override
    public JSONObject shipmentPlanStatistics1Export(ShipmentPlanStatistics1Req req) {
        List<ShipmentPlanStatistics1Res> statistics1ResList=getStatistics1ResList(req);
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getTitleInfo();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if(CollectionUtils.isEmpty(statistics1ResList)){
            obj.put("data", data);
            return obj;
        }
        excelInfoExport(data,statistics1ResList);
        obj.put("data", data);
        return obj;
    }

    public JSONArray getTitleInfo(){
        JSONArray obj=new JSONArray();
        obj.add("序号");
        obj.add("计划编号");
        obj.add("制单日期");
        obj.add("出运日期");
        obj.add("客户名称");
        obj.add("业务模式");
        obj.add("销售合同号");
        obj.add("采购单号");
        obj.add("供应商名称");
        obj.add("产品编码");
        obj.add("规格编号");
        obj.add("中文名称");
        obj.add("英文名称");
        obj.add("中文描述");
        obj.add("英文描述");
        obj.add("出运计划数量");
        obj.add("出运明细数量");
        obj.add("未出运明细数量");
        obj.add("结汇数量");
        obj.add("未结汇数量");
        obj.add("产品单位");
        obj.add("产品类型");
//        obj.add("成本单价");
        obj.add("业务员");
        obj.add("操作员");
        return obj;
    }
    public void excelInfoExport(JSONArray data,List<ShipmentPlanStatistics1Res> list){
        //出运计划数量
        BigDecimal shipmentPlanNum = new BigDecimal("0");
        //出运明细数量
        BigDecimal carryPlanProductNum = new BigDecimal("0");
        //未出运明细数量
        BigDecimal unCarryPlanProductNum = new BigDecimal("0");
        //结汇数量
        BigDecimal billExchangeInfoNum = new BigDecimal("0");
        //未结汇数量
        BigDecimal unBillExchangeInfoNum = new BigDecimal("0");
        //成本单价
        BigDecimal costPrice = new BigDecimal("0");

        Integer i=0;
        for (ShipmentPlanStatistics1Res vo: list) {
            JSONArray infoList = new JSONArray();
            infoList.add(++i);
            infoList.add(getNotNullOfStringInfo(vo.getShipmentNo()));
            infoList.add(getNotNullOfStringInfo(vo.getCreateTimeStr()));
            infoList.add(getNotNullOfStringInfo(vo.getShipmentDateStr()));
            infoList.add(getNotNullOfStringInfo(vo.getCustomerName()));
            infoList.add(getNotNullOfStringInfo(vo.getBusinessMode()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesContractNo()));
            infoList.add(getNotNullOfStringInfo(vo.getStockNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSupplyerName()));
            infoList.add(getNotNullOfStringInfo(vo.getGoodsCode()));
            infoList.add(getNotNullOfStringInfo(vo.getSpecNo()));
            infoList.add(getNotNullOfStringInfo(vo.getGoodsCName()));
            infoList.add(getNotNullOfStringInfo(vo.getGoodsEName()));
            infoList.add(getNotNullOfStringInfo(vo.getGoodsCDesc()));
            infoList.add(getNotNullOfStringInfo(vo.getGoodsEDesc()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getShipmentPlanNum()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getCarryPlanProductNum()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getUnCarryPlanProductNum()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getBillExchangeInfoNum()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getUnBillExchangeInfoNum()));
            infoList.add(getNotNullOfStringInfo(vo.getProductUnit()));
            infoList.add(getNotNullOfStringInfo(vo.getProductType()));
//            infoList.add(getNotNullOfBigDecimalInfo(vo.getCostPrice()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesmanName()));
            infoList.add(getNotNullOfStringInfo(vo.getExecutorName()));
            if(StringUtil.isNotEmpty(vo.getShipmentPlanNum())){
                shipmentPlanNum = shipmentPlanNum.add(vo.getShipmentPlanNum());
            }
            if(StringUtil.isNotEmpty(vo.getCarryPlanProductNum())){
                carryPlanProductNum = carryPlanProductNum.add(vo.getCarryPlanProductNum());
            }
            if(StringUtil.isNotEmpty(vo.getUnCarryPlanProductNum())){
                unCarryPlanProductNum = unCarryPlanProductNum.add(vo.getUnCarryPlanProductNum());
            }
            if(StringUtil.isNotEmpty(vo.getBillExchangeInfoNum())){
                billExchangeInfoNum = billExchangeInfoNum.add(vo.getBillExchangeInfoNum());
            }
            if(StringUtil.isNotEmpty(vo.getUnBillExchangeInfoNum())){
                unBillExchangeInfoNum = unBillExchangeInfoNum.add(vo.getUnBillExchangeInfoNum());
            }
            if(StringUtil.isNotEmpty(vo.getCostPrice())){
                costPrice = costPrice.add(vo.getCostPrice());
            }
            data.add(infoList);
        }
        //合计
        JSONArray infoList = new JSONArray();
        infoList.add("合计");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add(shipmentPlanNum);
        infoList.add(carryPlanProductNum);
        infoList.add(unCarryPlanProductNum);
        infoList.add(billExchangeInfoNum);
        infoList.add(unBillExchangeInfoNum);
        infoList.add("");
        infoList.add("");
//        infoList.add(costPrice);
        infoList.add("");
        infoList.add("");
        data.add(infoList);
    }

    @Override
    public Integer surplusAmount(String wxAndBhFlag,Integer shipmentPlanProductId,Integer id,String exportCode, String productCode,String specNo) {
        if (wxAndBhFlag.equals("w")){//外销
            return shipmentPlanDAO.exportSurplusAmount(shipmentPlanProductId,id,exportCode,productCode,specNo);
        }else {//备货
            return shipmentPlanDAO.taskSurplusAmount(shipmentPlanProductId,exportCode,productCode,specNo);
        }

    }
}
